package com.tubeonfire.controller;

import java.io.IOException;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.tubeonfire.entity.Playlist;
import com.tubeonfire.entity.Tube;
import com.tubeonfire.model.PlaylistModel;
import com.tubeonfire.model.TubeModel;
import com.tubeonfire.util.StringHelper;

public class PlaylistController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BlobstoreService blobstoreService = BlobstoreServiceFactory
			.getBlobstoreService();

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		String path = ((HttpServletRequest) request).getRequestURI();
		String action = "";
		String[] splittedURI = path.split("/");
		// if length = 3, this is for action request.
		if (splittedURI.length == 3) {
			action = splittedURI[splittedURI.length - 1];
			System.out.println("Do action : " + action);
			// create new playlist, return create page.
			if (action.equalsIgnoreCase("create")) {
				if (user != null) {
					request.getRequestDispatcher("/playlist_create.jsp")
							.forward(request, response);
				} else {
					response.getWriter().println("User's not login.");
				}
			}
			// return playlist manager page.
			else if (action.equalsIgnoreCase("manager")) {
				if (user != null) {
					List<Playlist> result = PlaylistModel.getByUserId(user
							.getUserId());
					if (result.size() > 0) {
						request.setAttribute("result", result);
						request.getRequestDispatcher("/playlist_manager.jsp")
								.forward(request, response);
					} else {
						response.getWriter().println("User have no playlist.");
					}
				} else {
					response.getWriter().println("User's not login.");
				}
			}
			// delete playlist, return manager page.
			else if (action.equalsIgnoreCase("delete")) {
				if (user != null) {
					String pid = request.getParameter("id");
					Playlist pl = PlaylistModel.getById(pid);
					if (pl.getUserFederatedId().equals(user.getUserId())) {
						pl.setStatus(4);
						PlaylistModel.update(pl);
						PlaylistModel.closePM();
						response.sendRedirect("/playlist/manager");
					} else {
						response.getWriter().println(
								"You don't have permission to do this action.");
					}
				} else {
					response.getWriter().println("User's not login.");
				}

			}
			// add video to playlist.
			else if (action.equalsIgnoreCase("add")) {
				if (request.getParameter("playlist_id") != null
						&& request.getParameter("video_id") != null) {
					Playlist plToAdd = PlaylistModel.getById(request
							.getParameter("playlist_id"));
					Tube tub = TubeModel.getByTubeId(request
							.getParameter("video_id"));
					if (tub != null && plToAdd != null) {
						List<Text> listTube = new ArrayList<Text>();
						if (plToAdd.getListTubes().size() > 0) {
							listTube = plToAdd.getListTubes();
						}
						Text tmpText = new Text(tub.toString());
						for (int i = 0; i < listTube.size(); i++) {
							if (listTube.get(i).equals(tmpText)) {
								listTube.remove(i);
								break;
							}
						}
						listTube.add(new Text(tub.toString()));
						plToAdd.setListTubes(listTube);
						PlaylistModel.update(plToAdd);
						PlaylistModel.closePM();
						System.out.println("Ok, video added to playlist");
					} else {
						response.getWriter().println(
								"Cannot add video to playlist.");
					}
				} else {
					response.getWriter().println(
							"Cannot add video to playlist.");
				}
			}
			// edit playlist.
			else if (action.equalsIgnoreCase("edit")) {
				if (user != null) {
					String pid = request.getParameter("id");
					Playlist pl = PlaylistModel.getById(pid);
					if (pl.getUserFederatedId().equals(user.getUserId())) {
						request.setAttribute("result", pl);
						request.getRequestDispatcher("/playlist_edit.jsp")
								.forward(request, response);
					} else {
						response.getWriter()
								.println(
										"You don't have permission to delete this playlist.");
					}
				} else {
					response.getWriter().println("User's not login.");
				}
			}
			// edit videos in playlist.
			else if (action.equalsIgnoreCase("edit_videos")) {
				if (user != null) {
					String pid = request.getParameter("id");
					Playlist pl = PlaylistModel.getById(pid);
					if (pl.getUserFederatedId().equals(user.getUserId())) {
						request.setAttribute("result", pl);
						request.getRequestDispatcher(
								"/playlist_edit_videos.jsp").forward(request,
								response);
					} else {
						response.getWriter()
								.println(
										"You don't have permission to delete this playlist.");
					}
				} else {
					response.getWriter().println("User's not login.");
				}
			}
			// remove clip from a playlist.
			else if (action.equalsIgnoreCase("remove_clip")) {
				if (user != null) {
					String id = request.getParameter("id");
					String pId = request.getParameter("pId");
					System.out.println(id);
					System.out.println(pId);
					Tube tub = TubeModel.getByTubeId(id);
					Playlist pl = PlaylistModel.getById(pId);
					if (pl != null && tub != null
							&& pl.getUserFederatedId().equals(user.getUserId())) {
						List<Text> newVideos = pl.getListTubes();
						for (int i = 0; i < newVideos.size(); i++) {
							Tube exitTub = new Tube();
							exitTub.transformString(newVideos.get(i).getValue());
							if (tub.getTubeId().equalsIgnoreCase(
									exitTub.getTubeId())) {
								newVideos.remove(i);
								break;
							}
						}
						pl.setListTubes(newVideos);
						PlaylistModel.update(pl);
						PlaylistModel.closePM();
						response.sendRedirect("/playlist/edit_videos?id="
								+ pl.getId());
					} else {
						response.getWriter()
								.println(
										"You don't have permission to delete this playlist.");
					}
				} else {
					response.getWriter().println("User's not login.");
				}
			}
		}
		// if length = 4, this is view detail playlist request.
		else if (splittedURI.length == 4) {
			if (user != null) {
				List<Playlist> pls = PlaylistModel
						.getByUserId(user.getUserId());
				Playlist pl = null;
				if (pls.size() > 0) {
					for (Playlist playlist : pls) {
						if (playlist.getId().equalsIgnoreCase(splittedURI[2])) {
							pl = playlist;
							break;
						}
					}
				}
				if (pl != null && pl.getListTubes().size() > 0) {
					request.setAttribute("result", pl);
					request.setAttribute("listPl", pls);
					request.getRequestDispatcher("/playlist_show.jsp").forward(
							request, response);
				} else {

				}
			} else {
				Playlist pl = PlaylistModel.getById(splittedURI[2]);
				if (pl != null && pl.getListTubes().size() > 0) {
					request.setAttribute("result", pl);
					request.getRequestDispatcher("/playlist_show.jsp").forward(
							request, response);
				} else {

				}
			}
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		if (user != null) {
			String action = req.getParameter("action");
			if (action.equalsIgnoreCase("create")) {
				Playlist pl = new Playlist();
				if (req.getParameter("title") != null) {
					pl.setTitle(new Text(req.getParameter("title")));
				}
				if (req.getParameter("description") != null) {
					pl.setDescription(new Text(req.getParameter("description")));
				}
				Map<String, List<BlobKey>> blobs = blobstoreService
						.getUploads(req);
				List<BlobKey> blobKeys = blobs.get("myFile");
				if (blobKeys != null && blobKeys.size() > 0) {
					pl.setPictureBlobKey(new Text(blobKeys.get(0)
							.getKeyString()));
				}
				SecureRandom random = null;
				for (int i = 0; i < 10; i++) {
					random = new SecureRandom();
					String id = new BigInteger(130, random).toString(32)
							.substring(0, 11);
					if (!PlaylistModel.isExits(id)) {
						pl.setId(id);
						break;
					}
					pl.setId(null);
				}
				pl.setUserFederatedId(user.getUserId());
				pl.setDoc(Calendar.getInstance().getTime());
				pl.setUpdate(Calendar.getInstance().getTime());
				pl.setAlias(new Text(StringHelper.getAliasByLanguage(pl
						.getTitle().getValue())));
				pl.setStatus(1);
				if (pl.isOk()) {
					PlaylistModel.add(pl);
					System.out.println("Add playlist ok.");
					resp.sendRedirect("/playlist/manager");
				} else {
					System.out.println("Playlist is invalid.");
					resp.sendRedirect("/playlist/create");
				}
			} else if (action.equalsIgnoreCase("edit")) {
				String id = req.getParameter("playlist_id");
				Playlist pl = PlaylistModel.getById(id);
				if (pl != null) {
					if (req.getParameter("title") != null) {
						pl.setTitle(new Text(req.getParameter("title")));
					}
					if (req.getParameter("description") != null) {
						pl.setDescription(new Text(req
								.getParameter("description")));
					}
					Map<String, List<BlobKey>> blobs = blobstoreService
							.getUploads(req);
					List<BlobKey> blobKeys = blobs.get("myFile");
					if (blobKeys != null && blobKeys.size() > 0) {
						pl.setPictureBlobKey(new Text(blobKeys.get(0)
								.getKeyString()));
					}
					pl.setUpdate(Calendar.getInstance().getTime());
					if (pl.isOk()) {
						PlaylistModel.update(pl);
						PlaylistModel.closePM();
						System.out.println("Save playlist ok.");
						resp.sendRedirect("/playlist/manager");
					} else {
						System.out.println("Playlist is invalid.");
						resp.sendRedirect("/playlist/create");
					}
				} else {
					System.out.println("Playlist is not avaiable !");
				}
			} else {

			}

		} else {
			System.out.println("User is not login.");
			resp.sendRedirect("/login");
		}
	}
}
